<template>
  <div>
    <el-form :model="content" label-width="120px"  ref="dataFormRef" >
      <el-form-item label="内容栏目">
        <el-cascader :placeholder="placeholder" v-model="content.scode" :options="tableDatas" :props="{label:'name',value:'id',children:'children',checkStrictly: true }" @change="handleChange" filterable />        
      </el-form-item>

      <el-form-item label="内容标题">
        <el-input v-model="content.title" />
      </el-form-item>

      <el-form-item label="发布时间">
        <el-col :span="11">
          <el-date-picker
            v-model="content.date"
            type="datetime"
            placeholder="请选择时间"
            style="width: 100%"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-col>        
      </el-form-item>
      
      <el-form-item label="内容">
          <div style="border: 1px solid #ccc ;width: 100%;" >
              <Editor :modelValue="content.content" @update:modelValue="handleChangeContent" style="height: 600px" />
        </div>
      </el-form-item>

      <el-form-item label="tags">
        <el-input v-model="content.tags" placeholder="请输入文章tag，英文逗号隔开" />
      </el-form-item>

      <el-form-item label="作者">
        <el-input v-model="content.author" />
      </el-form-item>

      <el-form-item label="来源">
        <el-input v-model="content.source" />
      </el-form-item>

      <el-form-item label="缩略图">
        <el-upload
          class="avatar-uploader"
          :action="`${path}/fileUploadAndDownload/upload`"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :headers="header"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>


      <el-form-item label="轮播多图">
        <el-upload
        v-model:file-list="fileList"
          class="avatar-uploader"
          :action="`${path}/fileUploadAndDownload/upload`"
          :before-upload="beforeAvatarUpload"
          :headers="header"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
        >
        <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="排序">
        <el-input-number :min="0" v-model="content.sorting" />
      </el-form-item>

      <el-form-item label="参数">
        <el-space :size="10" >
          <el-switch :active-value = "'1'" :inactive-value = "'0'" v-model="content.istop" inline-prompt active-text="置顶" inactive-text="置顶" />
          <el-switch :active-value = "'1'" :inactive-value = "'0'"  v-model="content.isrecommend" inline-prompt active-text="推荐" inactive-text="推荐"  />
          <el-switch :active-value = "'1'" :inactive-value = "'0'"  v-model="content.isheadline" inline-prompt active-text="头条" inactive-text="头条"  />
        </el-space>

      </el-form-item>

      <el-form-item label="SEO">
        <el-input v-model="content.description" />
      </el-form-item>
      <el-form-item label="浏览权限">
        <el-select v-model="content.gid" placeholder="不限制">
          <el-option label="初级会员" value="1" />
          <el-option label="中级会员" value="2" />
          <el-option label="高级会员" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="权限类型">
        <el-select v-model="content.gtype" placeholder="请选择">
          <el-option label="小于" value="1" />
          <el-option label="小于等于" value="2" />
          <el-option label="等于" value="3" />
          <el-option label="大于等于" value="4" />
          <el-option label="大于" value="5" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button>返回</el-button>
      </el-form-item>
    </el-form>

    <el-dialog v-model="dialogVisible">
      <img w-full :src="imageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref,reactive, onMounted} from 'vue'
import { ElMessage,ElForm } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useUserStore } from '@/pinia/modules/user'
import { sjbzGetidContent,sjbzCreateContent,sjbzDeleteContent,sjbzUpdateContent } from '@/api/contents/sjbz.js'
import { sjbzGetCategory,sjbzGetidCategory } from '@/api/categorys/sjbz.js'
import Editor from '@/components/editor/index.vue';
import { useRoute,useRouter } from 'vue-router';
import { formatDate } from '@/utils/format'
const route = useRoute()
const router = useRouter()

const path = ref(import.meta.env.VITE_BASE_API)
const imageUrl = ref('')
const nowdatetime = ref(formatDate(new Date()))
const tableDatas = ref([])

const fileList = ref([])
const dataFormRef = ref(ElForm);

const placeholder = ref('')

let content = reactive({
  id:null,
  acode:'cn',
  scode:'',
  title: '',
  content:'',
  description: '',
  date : nowdatetime ,
  author : '' ,
  tags : '' ,
  source:'本站',
  ico:'',
  pics:[],
  sorting:255,
  status:'1',
  istop:'0',
  isrecommend:'0',
  isheadline:'0',
  create_time:nowdatetime,
  gid:'',
  gtype:'',
})

const GetidContent = async(params) => {
   var response = await sjbzGetidContent(params)
    response.data.content = escape2Html(response.data.content)
      content.id = response.data.id
      content.scode = response.data.scode
      content.title = response.data.title
      content.content = response.data.content
      content.description = response.data.description
      content.date = response.data.date 
      content.tags = response.data.tags 
      content.author = response.data.author 
      content.source = response.data.source
      content.ico=response.data.ico
      content.pics=response.data.pics
      content.sorting = response.data.sorting
      content.istop = response.data.istop
      content.isrecommend=response.data.isrecommend
      content.isheadline=response.data.isheadline
      content.create_time = response.data.create_time
      content.gid=response.data.gid
      content.gtype=response.data.gtype
      imageUrl.value = response.data.ico
      if(response.data.pics) {
        fileList.value = JSON.parse( response.data.pics)
      }
      GetidCategory({"id":content.scode})
  //  return result
}
function  escape2Html(str) {
	  var  arrEntities={ 'lt' : '<' , 'gt' : '>' , 'nbsp' : ' ' , 'amp' : '&' , 'quot' : '"' };
	  return  str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function (all,t){ return  arrEntities[t];});
}
const handleChange = () => {
  ElMessage({
    message: '修改栏目',
    type: 'warning',
  })
}

const handleChangeContent = (e) => {
  content.content =  e
}
function  html2Escape(sHtml) {
	  return  sHtml.replace(/[<>& "]/g,function(c){return {'<':'&lt;','>':'&gt;','&':'&amp;','" ': '&quot;' }[c];});
}

onMounted(() => {
  const {token} = useUserStore()
  header.value['x-token'] = token
  var contentid = history.state.id
  if( contentid != undefined ){
    GetidContent({"id":contentid})
     
      //   })
  }
  getList()
})

const header = ref({
  'x-token': ''
})
const getList = async() => {
  const { data } = await sjbzGetCategory()
    tableDatas.value = data
}
const GetidCategory = async(params) => {
    const cataName = await sjbzGetidCategory(params)
    placeholder.value = cataName.data.name
}

const CreateContent = async(data) => {
  const result = sjbzCreateContent(data)
  return result
}

const UpdataContent = async(data) => {
  const result = sjbzUpdateContent(data)
  return result
}


const handleAvatarSuccess = (
  response,
  uploadFile
) => {
  content.ico = response.data.file.url
  imageUrl.value = response.data.file.url
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('图片必须是PNG或JPG格式')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能大于 2MB!')
    return false
  }
  return true
}

const onSubmit = () => {
  var temp = Array();
  for(var ia = 0 ; ia < fileList.value.length ; ++ia ){
    if(fileList.value[ia].response){      
      temp.push({"url":fileList.value[ia].response.data.file.url})
    } else{
      temp.push({"url":fileList.value[ia].url})
    }
    
  }
  content.pics = JSON.stringify( temp)
  content.scode = content.scode[content.scode.length - 1].toString()
  if(content.id == null && content.id  == 0) {
    var result = CreateContent(content)
  } else {
    var result = UpdataContent(content)
  }
  result.then( response => {
    if(response.code == 0){
      ElMessage.success(response.msg)
      router.push({path:"/layout/contents/sjbzcontents"})
    } else {
      ElMessage.error(response.msg)
    }
  })

}

const handleRemove  = (uploadFile, uploadFiles) => {
  
}
const dialogVisible = ref(false)
const handlePictureCardPreview  = (uploadFile) => {
  dialogVisible.value = true
}

</script>


<style lang="scss" scoped>
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>